<template>
  <div class="customer" v-show="isEnd">
    <div class="email-customer" style="margin-top: 10px">
      <!-- 列表数据展示-->
      <div class="detail list-table" :style="{maxHeight:$height-285+'px',overflowY:'auto'}" v-loading="loading">
        <el-checkbox v-model="checked" @change="selectAll" class="select-all"></el-checkbox>
        <div v-for="item,i in data" :key="i">
          <h1 class="title-table" v-show="item.total>0">
            {{item.title}}({{item.total}})
          </h1>
          <table class="table-detail">
            <tbody>
            <tr v-for="itemSon,i in item.list" :key="i" :class="{'active':itemSon.readStatus==1}">
              <td style="padding-left: 14px;width: 14px">
                <input type="checkbox" v-model="tEmailInfoIds" :value="itemSon.temailInfoId"></td>
              <td style="width: 30px;text-align: center">
                <!--是否建档-->
                <img v-if="itemSon.emailCustomerVO.type ==0" title="陌生人"
                     src="../../../../public/img/email/icon/icon-people.png" class="delivery-img"
                     alt="陌生人">
                <img v-else-if="itemSon.emailCustomerVO.type ==4" title="公海客户"
                     src="../../../../public/img/email/icon/icon-common.png" class="delivery-img"
                     alt="公海客户">
                <img v-else-if="itemSon.emailCustomerVO.type ==2" v-else title="同事建档客户"
                     src="../../../../public/img/email/icon/icon-worker.png" class="delivery-img"
                     alt="同事建档客户">
                <img v-else-if="itemSon.emailCustomerVO.type ==3" v-else title="共享客户"
                     src="../../../../public/img/email/icon/icon-share.png" class="delivery-img"
                     alt="共享客户">
                <img v-else title="建档客户" src="../../../../public/img/email/icon/icon-customer.png"
                     class="delivery-img" alt="建档客户">
              </td>
              <td width="270px" @click="toDetail(itemSon)">
                <span class="more" style="width: 260px;padding-right:10px;" v-html="filterEmail(itemSon)"></span>
              </td>
              <td :title="itemSon.emailSubject" @click="toDetail(itemSon)">
                  <span class="more" style="max-width: 350px">
                      <!--0.阿里巴巴询盘-->
                    <img v-show="itemSon.alibabaInquiry"  title="阿里巴巴询盘邮件" src="../../../../public/img/email/icon/alibaba.png"
                         class="alibaba" alt="建档客户">
                    <!--1.紧急图标 -->
                     <img v-if="parseInt(itemSon.emaileDelivery)==2" title="紧急邮件"
                          src="../../../../public/img/email/icon/icon-emps.png" class="delivery-img" alt="紧急邮件">
                    <!--2.是否回复-->
                      <img v-if="parseInt(itemSon.emailReply)==1" title="已回复"
                           src="../../../../public/img/email/icon/icon-replay.png" alt="" class="delivery-img">
                    {{itemSon.emailSubject}}
                  </span>
              </td>
              <td style="width: 200px">
                <el-tag closable
                        v-for="itemElse in itemSon.emailLabelList"
                        :key="itemElse.labelName" :color="itemElse.labelColor"
                        @close="handleClose(itemElse.temailLabelId)">
                  {{itemElse.labelName}}
                </el-tag>
              </td>
              <td width="150px" :title="itemSon.sendTime" @click="toDetail(itemSon)">
                <span class="time">{{itemSon.sendTime}}</span>
              </td>
              <td width="90px" class="make-td">
                <!-- 待办邮件-->
                <el-tooltip placement="top" v-if="itemSon.finish==1">
                  <div slot="content">待处理事件:<br/>{{itemSon.processTime}}</div>
                  <img  src="../../../../public/img/email/icon/icon-dealed.png"
                       @click="toComplete(itemSon.temailInfoId)" class="delivery-img" alt="邮件附件">
                </el-tooltip>
                <img v-else src="../../../../public/img/email/icon/icon-deal.png"
                     @click="toTimeDeal(itemSon.temailInfoId,itemSon.processTime)"
                     title="标记为待办邮件" class="delivery-img" alt="标记为待办邮件">
                <span>
                    <img v-if="parseInt(itemSon.fixed)==0" src="../../../../public/img/email/icon/icon-fix.png"
                         @click="fixedTop(itemSon.temailInfoId,1)"
                         title="固定邮件" class="delivery-img" alt="固定邮件">
                  <img v-else src="../../../../public/img/email/icon/icon-fixed.png"
                       @click="fixedTop(itemSon.temailInfoId,0)"
                       title="取消固定" class="delivery-img" alt="取消固定">
                  </span>
                <img src="../../../../public/img/email/icon/icon-del.png" @click="delEmail(itemSon.temailInfoId)"
                     title="删除邮件" class="delivery-img" alt="删除邮件">
                <!-- 附件-->
                <img v-show="itemSon.attachmentNumber>0" src="../../../../public/img/email/icon/icon-file.png"
                     title="邮件附件" class="delivery-img" alt="邮件附件">
              </td>
            </tr>
            </tbody>
          </table>
        </div>
      </div>
      <div class="empty" v-show="total==0">
        <img src="../../../../public/img/empty.png" alt="">
      </div>
      <el-pagination class="fixed"
                     background align="right"
                     @current-change="handleCurrent"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="size"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>
      <!-- 时间选择-->
      <TimeDialog ref="timeDialog" @getData="getData"></TimeDialog>
      <!-- 分发弹框-->
      <TranslateDialog ref="translateDialog" @getData="getData"></TranslateDialog>
      <!-- 新增标签-->
      <LabelDialog ref="labelDialog" @newLabel="newLabel"></LabelDialog>
      <!-- 时间选择-->
      <el-dialog :visible.sync="dialogVisible" width="500px"
                 :close-on-click-modal="false" :close-on-press-escape='false'
                 title="选择稍后处理的时间">
        <el-form ref="form" label-width="100px">
          <el-form-item label="自定义时间" style="margin: 40px 0">
            <el-date-picker size="small" v-model="nextTime" align="center" value-format="yyyy-MM-dd HH:mm:ss"
                            placeholder="自定义时间" :picker-options="pickerOptions"
                            type="datetime" :clearable="false">
            </el-date-picker>
            <!-- 底部按钮-->
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" align="right">
          <el-button @click="cancel" size="mini">取 消</el-button>
          <el-button type="primary" size="mini" @click="submitTime">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 归档文件-->
      <DocDialog ref="docDialog" @dealFoldID="dealFoldID"></DocDialog>
    </div>
  </div>
</template>

<script>
    import {getHour, getNextDate, getDate, getNext, getTimeEmailList,getDiffList} from "@/util/util"
    import {
        delEmail,
        emptyEmail,
        removeEmail,
        labelEmail,
        delLabel,
        getEmail,
        nextEmail,
        completeEmail,
        emptyAll,
        fixTop,
        getEmailStream
    } from "@/api/mail/make"
    import {queryEmailTypeList} from "@/api/mail/customer/slider"
    import {mapState} from 'vuex'
    import LabelDialog from "@/components/mail/dialog/LabelDialog";
    import TimeDialog from "@/components/mail/dialog/TimeDialog";
    import TranslateDialog from "@/components/mail/dialog/TranslateDialog";
    import DocDialog from "@/components/mail/dialog/DocDialog";
    import {getRead} from "@/api/mail/write";

    export default {
        name: "EmailList",
        props: ['boxID','name'],
        components: {LabelDialog, TimeDialog, TranslateDialog, DocDialog},
        data() {
            return {
                isReceiving:false,
                loading:false,
                isRebound:false,
                isFixed: 0,
                dialogVisible: false,
                theEmail: '',
                total: 0,
                currentPage: 1,
                showHeader: false,
                checked: false,
                searchContent: '',
                data: [],
                list: [],
                size: 20,
                targetLabel: '',
                targetRemove: '',
                tEmailInfoIds: [],//所选邮件列表
                emailList: [],
                targetTime: '',
                todayTime: '',
                nextWeek: '',
                nextTime: '',
                userId: '',
                nextEmail: '',
                pickerOptions: {
                    disabledDate: time => {
                        return time.getTime() < Date.now() - 8.64e7
                    }

                },
                listAll: [],
                archiveFolderId: '',
                //新增
                moveArchiveFolderId: '',
                isEnd: false
            }
        },
        computed: {
            ...mapState(['common']),
        },
        watch: {
            dialogVisible(val, old) {
                if (!val) {
                    this.targetTime = ''
                }
            },
            $route(to) {
                this.theEmail = to.params.id;
                this.getData();
            }
        },
        mounted() {

            this.todayTime = getHour();
            this.nextWeek = getNextDate();
            const res = this.$route.params.id;
            if (res == -1) {
                this.isEnd = true;
                return;
            }
            this.theEmail = res;
            this.getData();
        },
        methods: {
            //已读
            getRead(temailInfoId) {
                getRead({temailInfoIds: [temailInfoId]}).then(res => {
                    this.dealResult(res, 1)
                })
            },
            //设为完成
            toComplete(tEmailInfoId) {
                completeEmail({temailInfoIds: [tEmailInfoId]}).then(res => {
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            handleChange(val) {
                this.moveArchiveFolderId = val[val.length - 1];
            },
            //清空
            emptyAll() {
                this.$confirm('清空已删除状态所有邮件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    emptyAll({userEmail: this.common.currentEmail}).then(res => {
                        this.dealResult(res)
                    })
                }).catch(() => {
                });
            },
            //分发
            translate() {
                if (!this.getSelectList()) return;
                if (this.tEmailInfoIds.length != 1) {
                    this.$message({
                        type: "success",
                        message: '只能选择一条邮件分发'
                    });
                    return;
                }
                this.$refs.translateDialog.init(this.tEmailInfoIds[0], this.name)
            },
            //作为附件发送
            elseEmail() {
                if (!this.getSelectList()) return;
                if (this.tEmailInfoIds.length != 1) {
                    this.$message({
                        type: "success",
                        message: '只能选择一条邮件作为附件发送'
                    });
                    return;
                }
                let title = '';
                this.listAll.map(item => {
                    if (item.temailInfoId == this.tEmailInfoIds[0]) {
                        title = item.emailSubject;
                    }
                })
                this.isRebound = true;
                getEmailStream(this.tEmailInfoIds[0]).then(res => {
                    this.isRebound = false;
                    const result = res.data.data;
                    const params = {
                        emailSubject: "Fw:" + title,
                        emailHtmlpicList: [
                            {
                                picName: result.fileName, fileSize: result.fileSize, fileGuid: result.fileUrl
                            }
                        ]
                    };
                    const ID = this.tEmailInfoIds[0]+"d";//row.id - 临时
                    if (getDiffList(ID,'emailListTab')==-1) {
                        this.$store.commit('SET_EMAILLISTTAB', {
                            type: 1, row: {
                                id: ID,
                                title: `Fw:${result.fileName}`,
                                file:JSON.stringify(params),
                                info:'',
                                state:2,
                                close: true
                            }
                        })
                    }else{
                        this.$store.commit('SET_EMAILLISTTAB', {type:0,current:ID})
                    }
                }).catch(err => {
                    this.isRebound = false;
                })
            },
            lookFixed() {
                this.isFixed = this.isFixed == 1 ? 0 : 1;
                this.handleCurrent(1)
            },
            //固定
            fixedTop(temailInfoId, type) {
                fixTop(temailInfoId, type).then(res => {
                    this.dealResult(res, 1)
                })
            },
            //收信
            toGet() {
                if (this.common.emailList.length == 0) {
                    this.$nextTick(() => {
                        this.bus.$emit('showNotBind')
                    });
                    return;
                }
                this.isReceiving=true;
                getEmail(this.common.currentEmail).then(res => {
                    this.dealResult(res)
                    this.isReceiving=false;
                }).catch(err => {
                    this.isReceiving=false;
                });
            },
            //全选
            selectAll(val) {
                if (val) {//全选
                    this.tEmailInfoIds = [];
                    this.listAll.map(item => {
                        this.tEmailInfoIds.push(item.temailInfoId)
                    })
                } else {
                    this.tEmailInfoIds = [];
                }
            },
            handleSizeChange(val) {
                this.size = val;
                this.$store.commit('SET_EMAILPAGESIZE', this.size)
                this.handleCurrent(1)
            },
            handleCurrent(val) {
                this.currentPage = val;
                this.$store.commit('SET_EMAILPAGE', this.currentPage)
                this.getData();
            },
            toWrite() {
                this.bus.$emit('refreshEmailChange', -1)
                this.$router.push('/mail/write/index')
            },
            //根据邮箱+类型获取对应的邮件列表数据
            getData() {
                this.loading=true;
                let params = {
                    query: this.searchContent,
                    emailAddress: this.theEmail,
                    current: this.currentPage,
                    size: this.size,
                    fixed: this.isFixed,
                    type: 1
                }
                queryEmailTypeList(params).then(res => {
                    this.loading=false;
                    this.isEnd=true;
                    this.total = res.data.total;
                    const list = res.data.records;
                    this.listAll = list;
                    this.data = getTimeEmailList(list);
                }).catch(()=>this.loading=false)
            },
            //去除标记 单个
            handleClose(id) {
                delLabel(id).then(res => {
                    this.dealResult(res, 1)
                }).catch(err => {
                    console.log(err)
                });
            },
            //去详情页面
            toDetail(row) {
                sessionStorage.setItem("lastpath", this.$route.fullPath)
                const ID = row.temailInfoId+"a";//row.id - 临时
                if (getDiffList(ID,'emailListCustomerTab')==-1) {
                    this.$store.commit('SET_EMAILLISTCUSTOMERTAB', {
                        type: 1, row: {
                            id: ID,
                            title: row.emailSubject,
                            state:1,
                            close: true
                        }
                    })
                }else{
                    this.$store.commit('SET_EMAILLISTTAB', {type:0,current:ID})
                }
            },
            //移动邮件
            toRemove(val) {
                if (!this.getSelectList()) {
                    this.targetRemove = '';
                    return;
                }
                if (val == '7') { //选择归档文件夹
                    this.$refs.docDialog.init();
                    this.targetRemove = '';
                } else {
                    this.moveEmail();
                }
            },
            dealFoldID(id) {
                this.moveArchiveFolderId = id;
                this.moveEmail();
            },
            moveEmail() {
                removeEmail({
                    boxId: this.moveArchiveFolderId ? 7 : this.targetRemove,
                    temailInfoIds: this.tEmailInfoIds,
                    archiveFolderId: this.moveArchiveFolderId
                }).then(res => {
                    this.dealResult(res)
                }).catch(err => {
                    console.log(err)
                });
            },
            //彻底删除
            emptyEmail() {
                if (!this.getSelectList()) return;
                this.$confirm('彻底删除该邮件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    emptyEmail(this.tEmailInfoIds).then(res => {
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    });
                }).catch(() => {
                });
            },
            //标记为待办
            toTimeDeal(id, processTime) {
                this.$refs.timeDialog.init(id, processTime);
            },
            //稍后处理
            toNextDeal() {
                if (!this.getSelectList()) {
                    this.targetTime = '';
                    return;
                }
                if (this.targetTime == '稍后处理') {
                    this.dialogVisible = true;
                } else {
                    this.submitTime()
                }
            },
            submitTime() {
                const time = this.getTime();
                if (time.indexOf('NaN') != -1) {//，没找到
                    this.$message({
                        type: "success",
                        message: '请选择自定义时间'
                    });
                    return;
                }
                this.targetTime = '';
                this.nextTime = '';
                this.dialogVisible = false;
                nextEmail({
                    processTime: time,
                    temailInfoIds: this.tEmailInfoIds
                }).then(res => {
                    this.dealResult(res, 1)
                }).catch(err => {
                    console.log(err)
                });
            },
            getTime() {
                switch (this.targetTime) {
                    case '1':
                        return getDate(0) + " " + this.todayTime + ":00";
                    case '2':
                        return getDate(1) + " 08:00:00";
                    case '3':
                        return getDate(2) + " 08:00:00";
                    case '4'://下周
                        let result;
                        if (this.nextWeek == '一') {
                            result = getNext(1)
                        } else if (this.nextWeek == '二') {
                            result = getNext(2)
                        } else if (this.nextWeek == '三') {
                            result = getNext(3)
                        }
                        return result + " 08:00:00";
                    case '稍后处理':
                        return this.nextTime;
                    default:
                        return
                }
            },
            newLabel() {
                var labelID = this.common.labelList[0].id
                labelEmail({
                    tagId: labelID,
                    temailInfoIds: this.tEmailInfoIds
                }).then(res => {
                    this.dealResult(res, 1)
                }).catch(err => {
                    console.log(err)
                });
            },
            //标记为
            toLabel(val) {
                const current = parseInt(val);
                this.targetLabel = '';
                if (current != -2 && !this.getSelectList()) return;
                switch (current) {
                    case -1:
                        this.isRead(-1);
                        break;
                    case -2:
                        if(this.theEmail){
                            this.isRead({
                                customerEmail: this.theEmail
                            });
                        }
                        break;
                    case -3:
                        this.$nextTick(() => {
                            this.$refs.labelDialog.init();
                        })
                        break;
                    default:
                        labelEmail({
                            tagId: current,
                            temailInfoIds: this.tEmailInfoIds
                        }).then(res => {
                            this.dialogTime = false;
                            this.dealResult(res, 1)
                        }).catch(err => {
                            console.log(err)
                        });
                }

            },
            isRead(params) {
                let param = {
                    temailInfoIds: this.tEmailInfoIds
                }
                if (params != -1) {
                    param = Object.assign({}, param, params)
                }
                getRead(param).then(res => {
                    this.dealResult(res, 1)
                })
            },
            //删除邮件
            delEmail(id) {
                let delArr = [];
                if (id) {
                    delArr.push(id)
                } else {
                    if (!this.getSelectList()) {
                        return;
                    } else {
                        delArr = this.tEmailInfoIds
                    }
                }
                if (delArr.length == 0) {
                    this.$message({
                        type: "success",
                        message: '请先选择要操作的邮件'
                    });
                    return;
                }
                this.$confirm('是否删除选中邮件?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: "success"
                }).then(() => {
                    //获取选中的邮件列表
                    delEmail(delArr).then(res => {
                        this.dealResult(res)
                    }).catch(err => {
                        console.log(err)
                    })
                }).catch(() => {
                });
            },
            dealResult(res, index) {
                if (res.data.success) {
                    this.checked = false;
                    this.targetRemove = this.targetLabel = '';
                    this.tEmailInfoIds = [];
                    this.bus.$emit('refreshEmailNum')
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                    let page = index ? this.currentPage : 1;
                    this.handleCurrent(page);
                } else {
                    this.$message({
                        type: "success",
                        message: res.data.msg
                    });
                }
            },
            //获取选择的邮件
            getSelectList(param) {
                if (this.tEmailInfoIds.length === 0) {
                    this.$message({
                        type: "success",
                        message: '请先选择要操作的邮件'
                    });
                    return false
                } else {
                    return true;
                }
            },
            filterHtml(str) {
                return decodeURIComponent(str).replace(/<[^<>]+>/g, '').replace(/&nbsp;/ig, '')
            },
            cancel() {
                this.dialogVisible = false;
                this.nextTime = '';
                this.targetTime = ''
            },
            filterEmail(row) {
                let image = parseInt(row.emailType) ? 'get' : 'put';
                let head = `<img v-else src="/img/email/icon/icon-${image}.png"
alt="" title="${ parseInt(row.emailType) ? '收件' : '发件'}" style="width: 16px;vertical-align: middle;margin-right: 3px">`
                const type = row.emailCustomerVO.type;
                if (type != 0) {
                    let str = row.emailCustomerVO.contactName + " | " + row.emailCustomerVO.enterpriseName;
                    return `<a href="javascript:void(0)" style="color: #8C8C8C;" title="${str}">${head + str}</a>`;
                }
                const name = row.senderNickName;
                const email = row.senderEmail;
                let str = '';
                if (name) {
                    if (name.indexOf("@") != -1) {
                        return `<a href="javascript:void(0)" style="color: #8C8C8C;" title="${name.split("@")[0] + " | " + email}">${head + name.split("@")[0] + " | " + email}</a>`;
                    }
                    str = name + " | " + email
                } else {
                    str = email.split("@")[0] + " | " + email
                }
                return `<a href="javascript:void(0)" style="color: #8C8C8C;" title="${str}">${head + str}</a>`;
            }
        },
    }
</script>


<style scoped lang="scss">
  @import "../../../styles/email";
  label.el-checkbox.select-all {
    position: absolute;
    left: 14px;
    top: 7px;
  }
</style>
